package com.swt.gap.service.impl;

import com.swt.gap.common.constant.CommonConstant;
import com.swt.gap.model.vo.CommonFileUploadVO;
import com.swt.gap.service.CommonFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommonFileServiceImpl implements CommonFileService {

    @Override
    public List<CommonFileUploadVO> uploadFile(MultipartFile[] files, String path) {
        List<CommonFileUploadVO> retValue = new ArrayList<>();
        CommonFileUploadVO fileUpload = new CommonFileUploadVO();

        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        for (MultipartFile multipartFile : files) {
            String originalFileName = multipartFile.getOriginalFilename();
            String saveFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern(CommonConstant.DATETIME_FORMAT_NOLINE)) + "_" + originalFileName;
            fileUpload.setOriginalFileName(originalFileName);
            fileUpload.setSavedFileName(saveFileName);
            String filePath = path + saveFileName;
            File dest = new File(filePath);
            try {
                multipartFile.transferTo(dest);
                fileUpload.setSuccess(true);
            } catch (IOException e) {
                e.printStackTrace();
                fileUpload.setSuccess(false);
            }
            retValue.add(fileUpload);
        }
        return retValue;
    }
}
